<?php
namespace api\helpers;

use Yii;
use yii\base\Component;
use yii\base\InvalidCallException;
use yii\helpers\ArrayHelper;
use api\common\models\Shops;

/**
 * 支付助手
 */
class Pay extends Component
{

    // 订单属性
    public $bodyParams;

    // 订单ID
    public $order_number;

    /**
     * 生成订单
     */
    public function getPayOrder()
    {
        $pay_point = $this->getPayPoint(); // 支付金额
        $arr = [
            'buyer_uid' => Yii::$app->user->identity->id, // 买家ID
            'seller_uid' => empty($this->bodyParams['bid']) ? '600032' : $this->bodyParams['bid'], //商家标识
            'total_points' => $pay_point, //总支付积分
            'total_canfetch_points' => (int)$this->bodyParams['type'] == 1 ? $pay_point : 0, // 总支付可提现积分'
            'total_charge_points' => (int)$this->bodyParams['type'] !== 1 ? $pay_point : 0,// '总支付充值金额',
            'order_number' => $this->order_number,
            'sub_order_list' => [[
                'seller_uid' => empty($this->bodyParams['bid']) ? '600032' : $this->bodyParams['bid'], //商家标识
                'pay_point' => $pay_point,
                'order_id' => $this->order_number,
                'goods_type' => (int)$this->bodyParams['type'] == '1' ? 'normal' : 'special', //商品类型
                'goods_info' => $this->getGoodsInfo()
            ]],
            'pwd' => $this->bodyParams['pwd'],
            'user_username' => $this->bodyParams['user_username'],
            'user_tel' => $this->bodyParams['user_tel'],
            'user_address' => $this->bodyParams['user_address'],
            'user_desc' => $this->bodyParams['user_desc'],
        ];

        return $arr;
    }


    /**
     * 生成goods_info 列表
     * 从客户端获取商品ID通过数据提取生成商品列表
     */
    public function getGoodsInfo()
    {
        // 提交到的数据处理
        $shopItems = ArrayHelper::getColumn($this->bodyParams['list'], function($element) {
            return ['shopid' => $element['id'], 'num' => $element['num']];
        });

        // 通过处理的数据获取商品信息
        $shopInfos = Shops::find()->where(['in', 'id', ArrayHelper::getColumn($shopItems, 'shopid')])->all();

        // 提取以键ID为值的索引
        $result = ArrayHelper::index($this->bodyParams['list'], 'id');

        $goods_info = ArrayHelper::getColumn($shopInfos, function($e) use($result){
            return [
                'goods_id' => $e->id,
                'goods_money' => $e->saleprice * 100,
                'goods_thumb' => $e->thumb,
                'goods_num' => $result[$e->id]['num'],
                'goods_desc' => $e->title 
            ];
        });

        return $goods_info;
    }


    /**
     * 获取商品合计价格
     */
    public function getPayPoint()
    {
        $goods_info = ArrayHelper::getColumn($this->getGoodsInfo(), function($e){
            return abs($e['goods_money'] * $e['goods_num']);
        });
        return array_sum($goods_info);
    }


}
